package com.woniu.account.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import com.woniu.account.dto.User.UserDto;
import com.woniu.account.form.User.*;
import com.woniu.account.model.User;
import com.woniu.account.param.User.*;
import com.woniu.account.service.UserService;
import com.woniu.exception.userexp.YogaException;
import com.woniu.model.Result;
import com.woniu.util.FileUtil;
import com.woniu.util.JwtUtil;
import com.woniu.util.OSSUtil;
import com.woniu.util.RedisUtil;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 杜岷芫
 * @since 2024年07月11日
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户操作信息接口")
public class UserController {
    @Autowired
    public UserService userService;
    @Resource
    private RedisUtil redisUtil;

    @Resource
    private OSSUtil ossUtil;
    @RestController
    @RequestMapping("/UserDemo")
    @Api(tags = "用户操作信息接口")
    public class userController {
        @Autowired
        public UserService userService;

        /**
         * 发送注册验证码的接口
         *
         * @param mobile
         * @return
         * @throws Exception
         */
        @GetMapping("/sendRegisterCode")
        @ApiOperation(value = "发送注册验证码的接口")
        public Result sendRegisterCode(@RequestParam("mobile") String mobile) throws Exception {
            userService.sendRegisterCode(mobile);
            return Result.getResult(null).setMsg("发送注册验证码成功").setCode(200);
        }
    }
    @PostMapping("/codeRegister")
    @ApiOperation(value = "用户点击注册接口")
    public Result registerByCode(@RequestBody CodeRegisterForm form)throws Exception{
            CodeRegisterParam param = BeanUtil.toBean(form, CodeRegisterParam.class);
            userService.CodeRegister(param);
            return Result.getResult().setCode(200).setMsg("注册成功");
    }


    //用户账号密码登录
    @PostMapping("/userlogin")
    @ApiOperation(value = "用户账号密码登录接口")
    public Result userlogin(@RequestBody UserInfoLoginForm form, HttpServletResponse response)throws Exception{
        UserDto dto  = userService.userlogin(BeanUtil.toBean(form, UserInfoLoginParam.class));
        Map<String , Object> acccessBody = new HashMap<>();
        String random = new Snowflake(1, 1).nextIdStr();
        acccessBody.put("random",random);
        acccessBody.put("userId",dto.getUserId());
        String accessToken = JwtUtil.createUserToken(acccessBody, 15);//生成一个短token
        String refreshToken = JwtUtil.createUserToken(acccessBody, 3*24*60);//生成一个长token
        //将长token保存到redis.createToken
        redisUtil.set(accessToken,refreshToken,3*24*60*60);
        //响应token给前端
        response.setHeader("token", accessToken);
        response.setHeader("Access-Control-Expose-Headers", "token");
        return Result.getResult().setData(dto).setMsg("登录成功");
    }
    @PostMapping("/updateImage")
    @ApiOperation("用户修改个人头像")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "file", value = "上传的图片文件", required = true, dataType = "org.springframework.web.multipart.MultipartFile", paramType = "form"),
//            @ApiImplicitParam(name = "token", value = "认证令牌", required = true, dataType = "string", paramType = "header")
//    })
    public Result updateImage(
//            UpdateUserImageForm form,
            @RequestParam("file") MultipartFile file,
            @RequestHeader String token)throws Exception{
        String refreshToken = redisUtil.get(token);
        Claims claims = JwtUtil.parseUserToken(refreshToken);
        Integer coachId = Integer.parseInt(JwtUtil.parseUserToken(refreshToken).get("userId").toString());
        if (!FileUtil.isImageFile(file.getInputStream())){
            throw  new YogaException(9999,"文件类型错误");
        }
        if (!((file.getOriginalFilename()) ==null)){
            String oldName = file.getOriginalFilename();
            String suffix = oldName.substring(oldName.lastIndexOf("."));
            String name = UUID.randomUUID().toString();
            String filePath = OSSUtil.uploadFile(file.getInputStream(), name + suffix, "jiangdashuai");
//            UpdateUserImageParam param = BeanUtil.toBean(form, UpdateUserImageParam.class);
            UpdateUserImageParam param = new UpdateUserImageParam();
            param.setUserId(coachId);
            param.setImage(filePath);
            userService.updateImage(param);
        }

        return Result.getResult().setMsg("修改个人头像成功");
    }

    @Transactional
    @PostMapping("/UpdateNickName")
    @ApiOperation("用户修改昵称")
    public Result updateNiceName(@RequestBody UpdateNickNameForm form, @RequestHeader String token) throws Exception {
        String refreshToken = redisUtil.get(token);
        Integer userId = Integer.parseInt(JwtUtil.parseUserToken(refreshToken).get("userId").toString());
        UpdateNickNameParam param = BeanUtil.toBean(form, UpdateNickNameParam.class);
        param.setUserId(userId);
        userService.UpdateNickName(param);
        return Result.getResult().setMsg("修改成功");
    }

    @GetMapping("/byId/{id}")
    @ApiOperation("根据id查找用户信息")
    public Result byId(@PathVariable("id") Integer id){
        User user = userService.getById(id);
        return Result.getResult().setData(BeanUtil.toBean(user,UserDto.class));
    }
    @Transactional
    @GetMapping("/UpdateUserPassword")
    @ApiOperation("修改密码")
    public  Result UpdateUserPassword(String userPass,@RequestHeader String token)throws Exception{
        String refreshToken = redisUtil.get(token);
        Integer userId = Integer.parseInt(JwtUtil.parseUserToken(refreshToken).get("userId").toString());
        UpdateUserPasswordParam param = new UpdateUserPasswordParam();
        param.setUserId(userId);
        param.setUserPass(userPass);
        userService.UpdateUserPassword(param);
        return Result.getResult().setMsg("修改密码成功");
    }
    @GetMapping("/UpdateUserPhone")
    @ApiOperation(value = "发送修改手机号验证码的接口")
    public Result UpdateUserPhone(@RequestParam("mobile") String mobile) throws Exception {
        userService.UpdateUserPhone(mobile);
        return Result.getResult(null).setMsg("发送修改手机号验证码成功").setCode(200);
    }

    /**
     *用户的手机号修改
     * 需要传的值  老的手机号 发送的验证码code  在传入新的手机号
     * @param
     * @return
     */
    @PostMapping("/codeUpdate")
    @ApiOperation(value = "用户修改手机号的接口")
    public Result codeUpdate(@RequestBody CodeUpdateParam form) throws  Exception{
        userService.codeUpdate(BeanUtil.toBean(form, CodeUpdateParam.class));
        return Result.getResult(null).setCode(200).setMsg("修改手机号成功");
    }
    /**
     *判断用户身份证是否合法
     *
     * @param
     * @return
     */
    @GetMapping("/inspectIdCard")
    @ApiOperation(value = "判断用户身份证是否合法")
    public Result inspectIdCard(String IdCard) throws Exception {
        boolean b = userService.inspectIdCard(IdCard);
        if (b) return Result.getResult().setMsg("身份证验证成功");

        return Result.getResult().setMsg("身份证不合法");
    }
    /**
     * 传入用户身份证号码 和姓名
     * @param form
     * @return
     */
    @ApiOperation("用户实名认证")
    @PostMapping("/realNameAuthentication")
    public Result<String> userRealNameAuthentication(@RequestBody RealNameAuthenticationForm form){
        String str = userService.userRealNameAuthentication(form);
        return Result.getResult(String.class).setMsg(str);
    }
    /**
     * 分页查询所有用户
     * @param form
     * @return
     * @throws Exception
     */
    @GetMapping("/pageAllUser")
    @ApiOperation("分页查询所有用户")
    public Result pageAllUser(PageAllForm form) throws YogaException {
        Page<User> page = userService.pageAllUser(BeanUtil.toBean(form, PageAllParam.class));
        return Result.getResult().setMsg("查询成功").setData(page).setCode(200);
    }
    @GetMapping("/loadUsersByIds")
    @ApiOperation("根据id查找用户信息")
    public Result<User> loadUsersByIds(Integer userId){
        User users = userService.loadUsersByIds(userId);
        return Result.getResult(User.class).setData(users);
    }

    @PostMapping("/load")
    @ApiOperation("分页查询所有用户")
    public Result load(LoadUserForm form) throws YogaException {
        PageInfo<UserDto> page = userService.load(BeanUtil.toBean(form, LoadUserParam.class));
        return Result.getResult().setMsg("查询成功").setData(page).setCode(200);
    }

}

